package me.cxlr.qinlauncher2.view.settings;

import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.preference.DropDownPreference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreferenceCompat;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import me.cxlr.qinlauncher2.R;
import me.cxlr.qinlauncher2.constants.Constants;
import me.cxlr.qinlauncher2.constants.LauncherAction;
import me.cxlr.qinlauncher2.dao.ActionDao;
import me.cxlr.qinlauncher2.dao.AppDao;
import me.cxlr.qinlauncher2.dao.KeyActionDao;
import me.cxlr.qinlauncher2.manager.SoftwareManager;
import me.cxlr.qinlauncher2.model.Action;
import me.cxlr.qinlauncher2.model.App;
import me.cxlr.qinlauncher2.model.AppAndAction;
import me.cxlr.qinlauncher2.model.KeyAction;
import me.cxlr.qinlauncher2.util.ResourceUtil;
import me.cxlr.qinlauncher2.util.SharedPreferencesUtil;
import me.cxlr.qinlauncher2.util.ThemeUtil;
import me.cxlr.qinlauncher2.util.ToastUtil;

/**
 * @author 酷安用户:山轮纸
 */
public class FunctionKeySettingsFragment extends PreferenceFragmentCompat {
    private AppDao appDao;
    private ActionDao actionDao;
    private KeyActionDao keyActionDao;

    DropDownPreference leftFunctionKeyClick;
    KeyAction leftFunctionKeyAction;

    DropDownPreference leftFunctionKeyLongClick;
    KeyAction leftFunctionKeyLongClickAction;

    DropDownPreference rightFunctionKeyClick;
    KeyAction rightFunctionKeyAction;

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preferences_function_key_settings, rootKey);

        appDao = new AppDao();
        actionDao = new ActionDao();
        keyActionDao = new KeyActionDao();

        // 菜单键单击
        leftFunctionKeyClick = findPreference("left_function_key_click");
        leftFunctionKeyAction = keyActionDao.findKeyActionByKeyNameAndKeyType("menu", 1);
        switch (leftFunctionKeyAction.getActionType()) {
            case 0:
                leftFunctionKeyClick.setSummary(R.string.left_function_key_click_summary_no);
                break;
            case 1:
                leftFunctionKeyClick.setSummary(getString(R.string.function_key_click_summary_open_app, leftFunctionKeyAction.getApp().getLabel()));
                break;
            case 2:
                String label = ResourceUtil.getString(requireActivity(), leftFunctionKeyAction.getAction().getResLabel());
                leftFunctionKeyClick.setSummary(getString(R.string.function_key_click_summary_action, label));
                break;
            default:
                break;
        }
        leftFunctionKeyClick.setOnPreferenceClickListener(v -> {
            dialogChoice(leftFunctionKeyAction, getString(R.string.left_function_key_click_title), 1);
            return true;
        });

        // 菜单键长按
        leftFunctionKeyLongClick = findPreference("left_function_key_long_click");
        leftFunctionKeyLongClickAction = keyActionDao.findKeyActionByKeyNameAndKeyType("menu_long_click", 1);
        switch (leftFunctionKeyLongClickAction.getActionType()) {
            case 0:
                leftFunctionKeyLongClick.setSummary(R.string.left_function_key_long_click_summary);
                break;
            case 1:
                leftFunctionKeyLongClick.setSummary(getString(R.string.function_key_click_summary_open_app, leftFunctionKeyLongClickAction.getApp().getLabel()));
                break;
            case 2:
                String label = ResourceUtil.getString(requireActivity(), leftFunctionKeyLongClickAction.getAction().getResLabel());
                leftFunctionKeyLongClick.setSummary(getString(R.string.function_key_click_summary_action, label));
                break;
            default:
                break;
        }
        leftFunctionKeyLongClick.setEnabled(false);

        // 返回键单击
        rightFunctionKeyClick = findPreference("right_function_key_click");
        rightFunctionKeyAction = keyActionDao.findKeyActionByKeyNameAndKeyType("back", 1);
        switch (rightFunctionKeyAction.getActionType()) {
            case 0:
                rightFunctionKeyClick.setSummary(R.string.right_function_key_click_summary_no);
                break;
            case 1:
                rightFunctionKeyClick.setSummary(getString(R.string.function_key_click_summary_open_app, rightFunctionKeyAction.getApp().getLabel()));
                break;
            case 2:
                String label = ResourceUtil.getString(requireActivity(), rightFunctionKeyAction.getAction().getResLabel());
                rightFunctionKeyClick.setSummary(getString(R.string.function_key_click_summary_action, label));
                break;
            default:
                break;
        }
        rightFunctionKeyClick.setOnPreferenceClickListener(v -> {
            dialogChoice(rightFunctionKeyAction, getString(R.string.right_function_key_click_title), 2);
            return true;
        });

        // start 虚拟菜单键启用自定义文字
        SwitchPreferenceCompat spcUseLeftVirtualFunctionKeyDiyWord = findPreference("use_left_virtual_function_key_diy_word");
        DropDownPreference ddpLeftVirtualFunctionKeyDiyWork = findPreference("left_virtual_function_key_diy_word");

        boolean flagUseLeftVirtualFunctionKeyDiyWord = SharedPreferencesUtil.getInstance().getBoolean("use_left_virtual_function_key_diy_word", false);
        String leftVirtualKeyDiyWork = SharedPreferencesUtil.getInstance().getString("left_virtual_function_key_diy_word", "");

        assert spcUseLeftVirtualFunctionKeyDiyWord != null;
        spcUseLeftVirtualFunctionKeyDiyWord.setOnPreferenceChangeListener(((preference, newValue) -> {
            boolean flagNewValue = Boolean.parseBoolean(newValue.toString());
            assert ddpLeftVirtualFunctionKeyDiyWork != null;
            ddpLeftVirtualFunctionKeyDiyWork.setEnabled(flagNewValue);
            return true;
        }));
        assert ddpLeftVirtualFunctionKeyDiyWork != null;
        ddpLeftVirtualFunctionKeyDiyWork.setEnabled(flagUseLeftVirtualFunctionKeyDiyWord);
        if ("".equals(leftVirtualKeyDiyWork)) {
            ddpLeftVirtualFunctionKeyDiyWork.setSummary(getString(R.string.left_virtual_function_key_diy_word_summary_no));
        } else {
            ddpLeftVirtualFunctionKeyDiyWork.setSummary(leftVirtualKeyDiyWork);
        }
        ddpLeftVirtualFunctionKeyDiyWork.setOnPreferenceClickListener(preference -> {
            this.dialogEditDiyWord(Constants.FUNCTION_KEY_MENU, ddpLeftVirtualFunctionKeyDiyWork);
            return true;
        });
        // end 虚拟菜单键启用自定义文字

        // start 虚拟返回键启用自定义文字
        SwitchPreferenceCompat spcUseRightVirtualFunctionKeyDiyWord = findPreference("use_right_virtual_function_key_diy_word");
        DropDownPreference ddpRightVirtualFunctionKeyDiyWork = findPreference("right_virtual_function_key_diy_word");

        boolean flagUseRightVirtualFunctionKeyDiyWord = SharedPreferencesUtil.getInstance().getBoolean("use_right_virtual_function_key_diy_word", false);
        String rightVirtualKeyDiyWork = SharedPreferencesUtil.getInstance().getString("right_virtual_function_key_diy_word", "");

        assert spcUseRightVirtualFunctionKeyDiyWord != null;
        spcUseRightVirtualFunctionKeyDiyWord.setOnPreferenceChangeListener(((preference, newValue) -> {
            boolean flagNewValue = Boolean.parseBoolean(newValue.toString());
            assert ddpRightVirtualFunctionKeyDiyWork != null;
            ddpRightVirtualFunctionKeyDiyWork.setEnabled(flagNewValue);
            return true;
        }));
        assert ddpRightVirtualFunctionKeyDiyWork != null;
        ddpRightVirtualFunctionKeyDiyWork.setEnabled(flagUseRightVirtualFunctionKeyDiyWord);
        if ("".equals(rightVirtualKeyDiyWork)) {
            ddpRightVirtualFunctionKeyDiyWork.setSummary(getString(R.string.right_virtual_function_key_diy_word_summary_no));
        } else {
            ddpRightVirtualFunctionKeyDiyWork.setSummary(rightVirtualKeyDiyWork);
        }
        ddpRightVirtualFunctionKeyDiyWork.setOnPreferenceClickListener(preference -> {
            this.dialogEditDiyWord(Constants.FUNCTION_KEY_BACK, ddpRightVirtualFunctionKeyDiyWork);
            return true;
        });
        // end 虚拟返回键启用自定义文字
    }

    @Override
    public void onResume() {
        super.onResume();
        ThemeUtil.initTheme();
    }

    /**
     * 选择动作或应用
     *
     * @param title       title
     * @param leftOrRight 1:left 2:right
     */
    private void dialogChoice(KeyAction keyAction, String title, int leftOrRight) {
        ArrayList<AppAndAction> appAndActionList = new ArrayList<>(16);
        List<Action> actionList = actionDao.findAllAction();
        if (actionList != null) {
            for (Action entity : actionList) {
                String label = ResourceUtil.getString(requireActivity(), entity.getResLabel());
                if (entity.getActionName().equals(LauncherAction.NO.getAction())) {
                    appAndActionList.add(AppAndAction.builder().id(entity.getId()).label(label).type(0).build());
                } else {
                    appAndActionList.add(AppAndAction.builder().id(entity.getId()).label(label).type(2).build());
                }
            }
        }
        List<App> appList = appDao.findAllApp();
        if (appList != null) {
            for (App entity : appList) {
                appAndActionList.add(AppAndAction.builder().id(entity.getId()).label(entity.getLabel()).type(1).build());
            }
        }

        String[] id = new String[appAndActionList.size()];
        String[] label = new String[appAndActionList.size()];
        int[] type = new int[appAndActionList.size()];
        for (int i = 0; i < appAndActionList.size(); i++) {
            id[i] = appAndActionList.get(i).getId();
            label[i] = appAndActionList.get(i).getLabel();
            type[i] = appAndActionList.get(i).getType();
        }

        AlertDialog alertDialog = new AlertDialog.Builder(requireContext())
                .setTitle(title)
                .setItems(label, (dialog, which) -> {
                    switch (leftOrRight) {
                        case 1:
                            updateLeftFunctionKeyAction(keyAction, id[which], type[which]);
                            break;
                        case 2:
                            updateRightFunctionKeyAction(keyAction, id[which], type[which]);
                            break;
                        default:
                            break;
                    }
                    dialog.dismiss();
                })
                .setPositiveButton("关闭", (dialog, which) -> dialog.dismiss())
                // .setCancelable(false)
                .create();
        alertDialog.show();
    }

    /**
     * 修改左按钮键动作
     *
     * @param keyAction 方向键动作
     * @param id        被选中id
     * @param type      id的类型
     */
    private void updateLeftFunctionKeyAction(KeyAction keyAction, String id, int type) {
        if (type == Constants.KEY_ACTION_TYPE_OPEN_APP) {
            App app = appDao.findAppById(id);
            keyAction.setActionType(1);
            keyAction.setAction(null);
            keyAction.setApp(app);
        } else if (type == Constants.KEY_ACTION_TYPE_ACTION) {
            Action action = actionDao.findActionById(id);
            keyAction.setActionType(2);
            keyAction.setAction(action);
            keyAction.setApp(null);
        } else if (type == Constants.KEY_ACTION_TYPE_NO) {
            keyAction.setActionType(0);
            keyAction.setAction(null);
            keyAction.setApp(null);
        }
        keyActionDao.updateKeyAction(keyAction);
        switch (keyAction.getActionType()) {
            case 0:
                leftFunctionKeyClick.setSummary(R.string.left_function_key_click_summary_no);
                break;
            case 1:
                leftFunctionKeyClick.setSummary(getString(R.string.function_key_click_summary_open_app, keyAction.getApp().getLabel()));
                break;
            case 2:
                String label = ResourceUtil.getString(requireActivity(), keyAction.getAction().getResLabel());
                leftFunctionKeyClick.setSummary(getString(R.string.function_key_click_summary_action, label));
                break;
            default:
                break;
        }
    }

    /**
     * 修改右按钮键动作
     *
     * @param keyAction 方向键动作
     * @param id        被选中id
     * @param type      id的类型
     */
    private void updateRightFunctionKeyAction(KeyAction keyAction, String id, int type) {
        if (type == Constants.KEY_ACTION_TYPE_OPEN_APP) {
            App app = appDao.findAppById(id);
            keyAction.setActionType(1);
            keyAction.setAction(null);
            keyAction.setApp(app);
        } else if (type == Constants.KEY_ACTION_TYPE_ACTION) {
            Action action = actionDao.findActionById(id);
            keyAction.setActionType(2);
            keyAction.setAction(action);
            keyAction.setApp(null);
        } else if (type == Constants.KEY_ACTION_TYPE_NO) {
            keyAction.setActionType(0);
            keyAction.setAction(null);
            keyAction.setApp(null);
        }
        keyActionDao.updateKeyAction(keyAction);
        switch (keyAction.getActionType()) {
            case 0:
                rightFunctionKeyClick.setSummary(R.string.right_function_key_click_summary_no);
                break;
            case 1:
                rightFunctionKeyClick.setSummary(getString(R.string.function_key_click_summary_open_app, keyAction.getApp().getLabel()));
                break;
            case 2:
                String label = ResourceUtil.getString(requireActivity(), keyAction.getAction().getResLabel());
                rightFunctionKeyClick.setSummary(getString(R.string.function_key_click_summary_action, label));
                break;
            default:
                break;
        }
    }

    /*** 自定义文字 */
    private AppCompatEditText etDiyWord;

    /**
     * 编辑文字
     *
     * @param functionKey        菜单键或者返回键
     * @param dropDownPreference 对应的DropDownPreference
     */
    private void dialogEditDiyWord(String functionKey, DropDownPreference dropDownPreference) {
        View view = getLayoutInflater().inflate(R.layout.dialog_edit_diy_word, null);

        etDiyWord = view.findViewById(R.id.dedw_et_diy_word);

        AlertDialog dialogCreate = new AlertDialog.Builder(requireContext())
                .setPositiveButton("保存", (dialog, which) -> {
                    if ("".equals(Objects.requireNonNull(etDiyWord.getText()).toString())) {
                        ToastUtil.show(requireContext(), "请输入自定义名称", ToastUtil.LENGTH_LONG);
                    } else {
                        switch (functionKey) {
                            case Constants.FUNCTION_KEY_MENU:
                                SharedPreferencesUtil.getInstance().setString("left_virtual_function_key_diy_word", etDiyWord.getText().toString());
                                dropDownPreference.setSummary(etDiyWord.getText().toString());
                                break;
                            case Constants.FUNCTION_KEY_BACK:
                                SharedPreferencesUtil.getInstance().setString("right_virtual_function_key_diy_word", etDiyWord.getText().toString());
                                dropDownPreference.setSummary(etDiyWord.getText().toString());
                                break;
                            default:
                                break;
                        }
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                .setTitle("编辑自定义文字")
                .setView(view)
                .setCancelable(true)
                .create();
        dialogCreate.show();
    }
}